package org.example.MyBatisPlus.Controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.MyBatisPlus.Service.IBookService;
import org.example.pojos.Book;
import org.example.pojos.ResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author : zhangbo
 * @data : 2024/7/30
 * @description :
 */
@RestController
@RequestMapping("/book")
@Slf4j
public class BookController {
    @Autowired
    private IBookService bookService;

    /**
     * 查询所有
     *
     * @return
     */
    @PostMapping("/getList")
    public ResultResponse getList(@PathVariable("currentPage") Integer currentPage,
                                  @PathVariable("pageSize")Integer pageSize,
                                  @RequestBody Book book) {
        //bug  如果当前页分页只有一条数据，21条，第三页，你执行了删除操作，页面刷新后会到第二页，但是会显示无数据
        //原因 total: 20, size: 10, current: 3,当前页码大雨了最大分页后的页码
        //解决 如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        IPage<Book> iPage;
        iPage = bookService.getPage(currentPage, pageSize,book);
        if (currentPage > iPage.getPages()) {
            iPage = bookService.getPage((int) iPage.getPages(), pageSize,book);
        }
        return new ResultResponse(true, iPage);
    }

    /**
     * 新增
     *
     * @param book
     * @return
     */
    @PostMapping("/insert")
    public ResultResponse insertBook(@RequestBody Book book) {
        return new ResultResponse(bookService.save(book), null);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public ResultResponse deleteBookById(@PathVariable("id") Integer id) {
        return new ResultResponse(bookService.removeById(id), null);
    }

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @GetMapping("/getById/{id}")
    public ResultResponse getById(@PathVariable("id") Integer id) {
        return new ResultResponse(true,"success", bookService.getById(id));
    }

    /**
     * 根据id修改
     *
     * @param book
     * @return
     */
    @PostMapping("/updateBooks")
    public ResultResponse updateBooks(@RequestBody Book book) {
        return new ResultResponse(true, bookService.updateById(book));
    }

    /**
     * 根据输入模糊查询
     *
     * @param str
     * @return
     */
    @PostMapping("/query")
    public ResultResponse queryBooks(String str) {
        return new ResultResponse(true, bookService.getBooks(str));
    }


    /**
     * 根据输入修改  0-查看，1-修改
     *
     * @param str
     * @return
     */
    @PostMapping("/modify")
    public ResultResponse modifyBooks(String str) {
        return new ResultResponse(true, bookService.modifyBooks(str));
    }

}
